package com.zbvc.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zbvc.dao.BookDao;
import com.zbvc.dao.impl.BookDaoImpl;
import com.zbvc.entity.Book;

/**
 * Servlet implementation class AddBookServlet
 */
@WebServlet(name = "addBook", urlPatterns = { "/addBook" })
public class AddBookServlet extends HttpServlet {
	// 成员
	private BookDao bookDao = new BookDaoImpl();
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddBookServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		// 获取页面中的所有数据
		String card = request.getParameter("card");
		String name = request.getParameter("name");
		String type = request.getParameter("type");
		String autho = request.getParameter("autho");
		String press = request.getParameter("press");
		int num = Integer.parseInt(request.getParameter("num"));
		
		// 先判断图书是否在数据库中已经存在  1005 select * from book where card=?
		boolean flag = bookDao.findBookByCard(card);
		if(!flag) {
			// 存入Book对象
			Book book = new Book();
			book.setAuthor(autho);
			book.setCard(card);
			book.setName(name);
			book.setPress(press);
			book.setType(type);
			book.setNum(num);
			int row = bookDao.insertBook(book);
			System.out.println("新增书籍"+row+"条");
			if(row>0) {
				response.sendRedirect("/bookManager/admin/admin_book.jsp");
			}else {
				
			}
		}else {
			// 提示用户该图书已经存在 window.history.back(-1) 网页回退一步，不刷新
			PrintWriter out = response.getWriter();
			out.print("<script>alert('该图书已存在，请重新添加'); window.history.back(-1);</script>");
			
		}
		
		
		
		
	}

}
